var proxy = require('http-proxy-middleware')
var target = require('../env.config').host

/**
 * 发往 java 后台
 */
module.exports = proxy('/api', {
  target,
  changeOrigin: true,
  logLevel: 'debug',
  pathRewrite: { '^/api': '/' },
  onProxyReq(proxyReq, req, res) {
    SessionUtil.setSessionValue(req,"reqTime",new Date());
    // 修改 header，使其包含用户信息
    if(req.session.user){
      let user = req.session.user || { agentId: null, phone: null, wechatInfoId:null }
      proxyReq.setHeader('agentId', user.agentId)
      proxyReq.setHeader('phone', user.phone)
      proxyReq.setHeader('wechatInfoId', user.wechatInfoId)
    }
  },

  onProxyRes(proxyRes,req,res){
    var body = [];
    proxyRes.on('data', function (chunk) {
      body.push(chunk);
    });
    proxyRes.on('end', function () {
      try {
        let result = JSON.parse(Buffer.concat(body).toString());
        //-1013代表后台用户已删除，需要清空session
        console.log("onProxyRes:登录失效",req.session.user)
        if(result.code==-1013){
          SessionUtil.clearLoginSession(req);
        }
      } catch (e) {
        console.error(e);
      }
    });
  }
})
